<?php
namespace Tbf\Bundle\DatabaseBundle\Command;
use Doctrine\DBAL\LockMode;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Tbf\Bundle\TbfBundle\Command\TbfCommand;
use Tbf\Bundle\TbfBundle\Exception\BusinessException;

/**
 * 在数据库里面替换字符串
 */
class ReplaceCommand extends TbfCommand
{
    protected function configure()
    {
        $this
            ->setName('tbf:database:replace')
            ->setDescription('replace some stuff in the table')
            ->addArgument('from', InputArgument::REQUIRED, 'replace from')
            ->addArgument('to',InputArgument::REQUIRED,'replace to')
            ->addOption('table',null,InputOption::VALUE_REQUIRED);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $from = $input->getArgument('from');
        $to = $input->getArgument('to');
        $input_table = $input->getOption('table');
        $db  = $this->getContainer()->get('tbf_database');
        $db->beginTransaction();
        if ($input_table===null){
            $tables = $db->getAllTableNameInDatabase();
        }else{
            $tables = array($input_table);
        }
        foreach($tables as $table){
            $db->replaceStringOneTable($table,$from,$to);
        }
        $db->commit();
    }
}
